package zw.car.server.netty.handler;

import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import zw.car.server.netty.NettyServer;
import zw.car.server.netty.util.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-09-11 10:42
 */
public class HexHandler extends ChannelInboundHandlerAdapter {
    Log log = LogFactory.get();
    private String url=HandUtil.getKey("host");
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf data=(ByteBuf)msg;
        String str=data.toString(Charset.defaultCharset());
        byte[] receiveMsgBytes = new byte[data.readableBytes()];
        data.readBytes(receiveMsgBytes);
        JSONObject json=new JSONObject();
        Map<String,Object> params=new HashMap<>();
        try{
            str=str.indexOf("$GPRMC")!=-1?str:HandUtil.convertHexToString(receiveMsgBytes);
            String tick="$GPRMC";
            str=HandUtil.convertHexToString(receiveMsgBytes);
            if(str.indexOf("$GPRMC")!=-1){
                System.out.println(str);
                String[] strings=HandUtil.GetStringArray(str);
                if(strings[2].indexOf("A")!=-1){
                    JSONObject obj=new JSONObject();
                    Coordinate coordinate=new Coordinate();
                    if((Math.floor(Double.parseDouble(strings[5]))+"").length()>5){
                        Double lng= Double.valueOf(strings[5].substring(3,strings[5].length()))/60;
                        Double lat= Double.valueOf(strings[3].substring(2,strings[3].length()))/60;
                        lng=Integer.parseInt(strings[5].substring(0,3))+lng;
                        lat=Integer.parseInt(strings[3].substring(0,2))+lat;
/*                        coordinate.setLongitude(lng);
                        coordinate.setLatitude(lat);*/
                        coordinate= EvilTransform.transform(lat,lng);
                    }else{
/*                        coordinate.setLongitude(Double.valueOf(strings[5]));
                        coordinate.setLatitude(Double.valueOf(strings[3]));*/
                        coordinate=EvilTransform.transform(Double.valueOf(strings[3]),Double.valueOf(strings[5]));
                    }
                    obj.put("x",coordinate.getLongitude());//经度
                    obj.put("y",coordinate.getLatitude());//纬度
                    obj.put("ag",strings[8]);//角度
                    obj.put("tm",System.currentTimeMillis()/1000L);//时间戳unix
                    obj.put("sp",Float.valueOf(strings[7])*1.852);//速度
                    obj.put("state",strings[2]);
                    json.put("imei",str.substring(0,str.indexOf(tick)));
                    json.put("dataContent",obj.toJSONString());
                    json.put("msgType",1);
                    params.put("imei",str.substring(0,str.indexOf(tick)));
                    params.put("lng",coordinate.toString());
                    params.put("data",json.toJSONString());
                    HttpUtil.post(url+"cargps",params);
                }
            }else if((receiveMsgBytes[0] & 0xFF)==0x78){
                    System.out.println("收到的数据："+HandUtil.bytesToHexString(receiveMsgBytes));
                    json.put("msgType",Integer.parseInt(Integer.toHexString((short)receiveMsgBytes[3] & 0xFF)));
                    JSONObject obj=HandUtil.DateDecodeHande(receiveMsgBytes,ctx);
                    if(json.getIntValue("msgType")==10||json.getIntValue("msgType")==69){
                        obj.put("x",obj.getString("locations").split(",")[0]);//经度
                        obj.put("y",obj.getString("locations").split(",")[1]);//纬度
                        obj.put("tm",System.currentTimeMillis()/1000L);//时间戳unix
                        params.put("lng",obj.getString("locations"));
                        obj.remove("locations");
                        obj.remove("info");
                        obj.remove("status");
                        json.put("dataContent",obj.toJSONString());
                        params.put("data",json.toJSONString());
                        json.put("imei",NettyServer.channelMap.get(ctx.channel().id().asShortText()).get("imei"));
                        params.put("imei",json.getString("imei"));
                        System.out.println(url);
                        HttpUtil.post(url+"usergps",params);
                    }else if(json.getIntValue("msgType")==8){
                        params.put("tick"," user");
                        params.put("imei",NettyServer.channelMap.get(ctx.channel().id().asShortText()).get("imei"));
                        params.put("state",1);
                        System.out.println(url);
                        HttpUtil.post(url+"getstate",params);
                    }
            }else if((receiveMsgBytes[0] & 0xFF)==0x95){
                json.put("imei","odb");
                params.put("data",HandUtil.DateDecode(receiveMsgBytes));
                System.out.println("ODB数据:"+params.get("data"));
                HttpUtil.post(url,params);
            }else if(receiveMsgBytes.length>15&&(receiveMsgBytes[15] & 0xFF)==0x01){
                String imei=HandUtil.convertHexToString(receiveMsgBytes);
                Map<String,Object> map=new HashMap<>();
                map.put("imei",imei.substring(0,15));
                map.put("tem",HandUtil.pinjie(receiveMsgBytes[18],receiveMsgBytes[19])/10);
                map.put("humidity",HandUtil.pinjie(receiveMsgBytes[20],receiveMsgBytes[21])/10);
                map.put("o3",HandUtil.pinjie(receiveMsgBytes[22],receiveMsgBytes[23]));
                try {
                    HttpUtil.get(url+"o3",map);
                }catch (Exception e){
                    //HttpUtil.get("http://1r6295i986.iask.in:41723/api/o3",map);
                    e.printStackTrace();
                }
                log.info("收到的数据 {} ℃",HandUtil.bytesToHexString(receiveMsgBytes));
                log.info("空气温度 {} ℃",HandUtil.pinjie(receiveMsgBytes[18],receiveMsgBytes[19])/10);
                log.info("空气湿度 {} %",HandUtil.pinjie(receiveMsgBytes[20],receiveMsgBytes[21])/10);
                log.info("臭味 {} PPM",HandUtil.pinjie(receiveMsgBytes[22],receiveMsgBytes[23]));
                System.out.println("收到的数据:"+HandUtil.bytesToHexString(receiveMsgBytes));
                System.out.println("空气温度："+HandUtil.pinjie(receiveMsgBytes[18],receiveMsgBytes[19])/10+"℃");
                System.out.println("空气湿度："+HandUtil.pinjie(receiveMsgBytes[20],receiveMsgBytes[21])/10+"%");
                System.out.println("臭味："+HandUtil.pinjie(receiveMsgBytes[22],receiveMsgBytes[23])+"PPM");
                System.out.println("电源电压："+HandUtil.pinjie(receiveMsgBytes[30],receiveMsgBytes[31])/10+"V");
                System.out.println("上传周期："+HandUtil.pinjie(receiveMsgBytes[32],receiveMsgBytes[33])+"s");
            }else if(str.indexOf("rfid") >= 0){
                System.out.println("rfid收到的数据"+HandUtil.bytesToHexString(receiveMsgBytes));
                System.out.println("rfid:"+str.substring(str.indexOf("rfid")+4,19));
//                System.out.println(receiveMsgBytes[19]);
//                System.out.println(receiveMsgBytes[26]);
                String rfidResult = HandUtil.bytesToHexString(receiveMsgBytes);
                System.out.println("card:"+rfidResult.substring(57,98));
                Map<String,Object> map = new HashMap<>();
                map.put("rfid",str.substring(str.indexOf("rfid")+4,19));
                map.put("card",rfidResult.substring(57,98));
                try {
                    HttpUtil.get(url+"rfid",map);
                }catch (Exception e){
                    //HttpUtil.get("http://1r6295i986.iask.in:41723/api/o3",map);
                    e.printStackTrace();
                }
            }
            else{
                byte[] start={0x01,0x03,0x00,0x00,0x00,0x10, 0x44,0x06};
                System.out.println("其他收到的数据:"+HandUtil.bytesToHexString(receiveMsgBytes));

                System.out.println("ASCII码："+str);
                if(str.equals("868221043329856")||str.indexOf("86")!=-1){
                    ByteBuf msg1= Unpooled.buffer();
                    msg1.writeBytes(start);
                    ctx.channel().writeAndFlush(msg1);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(msg);
        }

    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有设备接入："+ctx.channel().id().asShortText());
    }

    //客户端断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端："+ctx.channel()+"断开连接");
        for (String key: NettyServer.channelMap.keySet()) {
            for (String ke:NettyServer.channelMap.get(key).keySet()) {
                 Channel obj= (Channel) NettyServer.channelMap.get(key).get(ke);
                if(obj.id().asShortText().equals(ctx.channel().id().asShortText())){
                    NettyServer.channelMap.remove(ctx.channel().id().asShortText());
                }
            }
        }
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.channel().close();
        //打印异常
        cause.printStackTrace();
    }


}
